<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Pictuer;
use App\Transformers\PictuerTransformer;
use App\Transformers\TagTransformer;
use App\Models\Tag;
class PictuersController extends Controller
{
    public function index(Request $request, Pictuer $pictuer)
    {
        $query = $pictuer->query();
        $page_limit = $request->page_limit ?: 30;
        $pages = 0;
        $tag = [];
        switch ($request->order) {
            case 'recent':
                $query->recent();
                break;

            default:
                $query->orderBy('id', 'desc');
                break;
        }
        if($request->name) {
            if($tag = Tag::where('url', $request->name)->first())
            {
                $pictuers = $query->whereHas('tags', function ($q) use ($tag) {
                    $q->where('url', $tag->url);
                })->with('tags')->orderBy('title')->paginate($page_limit);
            } else {
                $pictuers = $query->paginate($page_limit);
            }
        } else {
            $pictuers = $query->paginate($page_limit);
        }
        return $this->response->paginator($pictuers, new PictuerTransformer())->addMeta('tag', $tag);
    }
}
